package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemo;
import cn.itcast.crm.domain.Customer;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
	private Customer customer = new Customer();
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate JmsTemplate;

	// 模型驱动
	@Override
	public Customer getModel() {

		return customer;
	}

	// 获取验证码
	@Action(value = "customer_sendSms")
	public String sendSms() {
		// 查询电话号码是否唯一

		// 生成短信验证码
		final String randomCode = RandomStringUtils.randomNumeric(4);
		System.out.println(randomCode);
		// 把生产的验证码保存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(customer.getTelephone(), randomCode);
		// 编辑短信内容
		final String msg = "尊敬的用户你好，本次获取的验证码为：" + randomCode;
		// 调用MQ服务，发送一条消息
		/*JmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", customer.getTelephone());
				mapMessage.setString("username", customer.getUsername());
				mapMessage.setString("smsRandomCode", randomCode);
				return mapMessage;
			}
		});*/
		/*
		 * try { SendSmsResponse response
		 * =SmsDemo.sendSms(customer.getTelephone(), customer.getUsername(),
		 * randomCode); if(response.getCode() != null &&
		 * response.getCode().equals("OK")) { System.out.println("发送短信成功!"); } }
		 * catch (ClientException e) {
		 * 
		 * e.printStackTrace(); }
		 */

		return NONE;

	}

	// 属性驱动
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 获取验证码
		String code = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(customer.getTelephone());
		if (code == null || !code.equals(checkcode)) {
			// 验证失败
			System.out.println("验证失败");
			return INPUT;
		} else {
			// 验证成功
			WebClient
					.create("http://localhost:8088/crm_management/services/customerService/customer")
					.type(MediaType.APPLICATION_JSON).post(customer);
			// 发送一封邮件
			// 生成激活码
			String activecode = RandomStringUtils.randomNumeric(24);
			// 把激活码保存到redis中
			redisTemplate.opsForValue().set(customer.getTelephone(),
					activecode, 24, TimeUnit.HOURS);
			String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
					+ MailUtils.activeUrl
					+ "?telephone="
					+ customer.getTelephone()
					+ "&activecode="
					+ activecode
					+ "'>速运快递邮箱绑定地址</a>";
			// MailUtils.activeUrl
			// 调用方法
			MailUtils
					.sendMail("激活邮件", content, customer.getEmail(), activecode);
			System.out.println("验证成功");
			return SUCCESS;
		}
	}

	// 属性驱动
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public String activeMail() throws Exception {
		// 解决乱码问题
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		// 获取激活码
		String activecodeRedis = redisTemplate.opsForValue().get(
				customer.getTelephone());
		// 判断激活码是否有效
		if (activecodeRedis != null && activecodeRedis.equals(activecode)) {
			// 有效
			Customer c = WebClient
					.create("http://localhost:8088/crm_management/services/customerService/customer/telephone/"
							+ customer.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println(c);
			if (c != null) {
				if (c.getType() != null && c.getType() == 1) {
					// 已经绑定
					ServletActionContext.getResponse().getWriter()
							.println("邮箱已经绑定过，无需重复绑定！");
					//
				} else {
					// 没有绑定
					WebClient.create(
							"http://localhost:8088/crm_management/services"
									+ "/customerService/customer/updatetype/"
									+ customer.getTelephone()).put(null);
					ServletActionContext.getResponse().getWriter()
							.println("邮箱绑定成功！");
				}

			}
		} else {
			// 无效
			ServletActionContext.getResponse().getWriter()
					.println("激活码无效，请登录系统，重新绑定邮箱！");
		}

		return NONE;
	}
	//用户登录
	@Action(value="customer_login",results={
			@Result(name="success",location="index.html#/myhome",type="redirect"),
			@Result(name="input",location="login.html",type="redirect")})
	public String login(){

		Customer c = WebClient.create(Constants.CRM_MANAGEMENT_HOST+"/crm_management/services/customerService/customer"
				+ "/login?telephone="+customer.getTelephone()+"&password="+customer.getPassword())
		.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		System.out.println(c);
		if(c==null){
			//登陆失败
			return INPUT;
		}else{
			//登陆成功
			ServletActionContext.getRequest().getSession().setAttribute("customer", c);
			return SUCCESS;
		}
	}
	
}
